import axios from 'axios'
import {
  Toast
} from 'vant'
// import store from '@/store'
import {
  getToken
} from '@/utils/auth'

// import { isMobileWeixin } from "./func"

import router from '@/router'

// create an axios instance
const service = axios.create({
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})
service.baseURL = process.env.VUE_APP_API_PREFIX // .env中配置的api前缀
console.log(service.baseURL)
/**
 * 请求拦截器
 * 每次请求前，如果存在token则在请求头中携带token
 */
service.interceptors.request.use(
  config => {
    // 获取token
    const token = getToken()
    token && (config.headers.Authorization = token)
    return config
  },
  error => {
    // do something with request error
    console.log(error, 'err') // for debug
    return Promise.reject(error)
  }
) 

service.interceptors.response.use(
  response => {
    console.log(response, 'response')

    const res = response.data

    if (res.code * 1 === 401) {
      Toast.fail({
        message: '登录超时，请重新登录',
        duration: 3 * 1000,
      });
      localStorage.removeItem('token')
      localStorage.removeItem("userInfo");
      router.push('/login')
      return
    }
    if (response.config.url.includes('insure/pay') || response.config.url.includes('insure/mergePay') || response.config.url.includes('insure/modifypay')) {
      return Promise.resolve(res)
    }
    if (res.code * 1 === 9000) {
      return Promise.resolve(res)
    }
    if (res.code * 1 !== 200) {
      // 处理自定义错误
      Toast.fail({
        message: res.msg || '接口报错' + '接口为：'+ response.config.url + '状态码：' + res.code,
        duration: 3 * 1000,
      });
      // return Promise.reject(new Error(res.msg || 'Error'))
    } else {
      return Promise.resolve(res)
    }
  },
  err => {
    console.log('err' + err) // for debug
    Toast.fail({
      message: err.msg || '系统异常',
      duration: 3 * 1000
    })
    return Promise.reject(err)
  }
)

export default service